package com.yc.damaimaven.controller;

import com.yc.damaimaven.entity.Result;
import com.yc.damaimaven.entity.User;
import com.yc.damaimaven.service.BizException;
import com.yc.damaimaven.service.IUserService;
import com.yc.damaimaven.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xw
 * @since 2024-07-09
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @RequestMapping("login")
    public Result login(@RequestBody User user, HttpSession session){

        try{
            User dbuser = userService.login(user);
            //登陆成功之后，将用户对象存入会话
            session.setAttribute("myinfo", dbuser);
            return Result.ok("登录成功!",dbuser);
        } catch (BizException e){
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("myinfo")
    public Result myinfo(@SessionAttribute(required = false) User myinfo){
        if(myinfo == null){
            return Result.error("未登录！");
        }
        return Result.ok("已登录！",myinfo);
    }

    @RequestMapping("logout")
    public ModelAndView logout(ModelAndView mav, HttpSession session){
        //销毁会话=>用户登录状态就失效了
        session.invalidate();
        mav.setViewName("redirect:/index.html");
        return mav;
    }

}
